package com.weihe.toolkit.json;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;


public class JsonToolkit {
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> T readObjectFromJsonString(String source, Class beanClass) {
		ObjectMapper objectMapper = new ObjectMapper();
		T map = null;
		try {
			objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
			map = (T)objectMapper.readValue(source, beanClass);
			return map;
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
		
	}
	public static String writeObjectToJsonString(Object obj) {
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (Exception ex) {
		    return null;
		}
	}
	
	public static String filterForJson(String inputString)  {
        StringBuffer outputStringbuffer = new StringBuffer();
        if(StringUtils.isNotBlank(inputString)){
        	for( int i= 0;i<inputString.length();i++){
        		char ch = inputString.charAt(i);
        		int n = (int)ch;
        		if(n>=32 && n != 34 && n != 92){
        			 outputStringbuffer.append(ch);
        		}
             }
        }
        
        return outputStringbuffer.toString().trim();
    }
	
	private static boolean isDateCharaters(String str){
        if (null==str || "".equals(str)) return false;    
        Pattern p =  Pattern.compile("([\\d-])+");  
        Matcher m = p.matcher(str);  
        return m.matches(); 
	}

	public static void main(String[] args){
//		String s = "[{\"id\":\"component1\",componentId":1,"channels":"0","keywords":"1","page":"1","pageSize":"11","style":"z-index: 2; top: 53px; left: 154px; box-shadow: -1px -1px 0px 0px rgba(0, 0, 0, 0.3); opacity: 1;"}]";
		System.out.println(JsonToolkit.isDateCharaters("2014"));
	}
	
}
